package com.gmj.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gmj.entity.Class;
import com.gmj.entity.Student;
import com.gmj.service.IClassService;
import com.gmj.service.IStudentService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gmj
 * @since 2022-01-29
 */
@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private IStudentService ss;
    @Autowired
    private IClassService cs;
    @GetMapping("/selectAll")
    public List<Student> selectAll(){
        List<Student> list = ss.list();
        List<Class> classList = cs.list();
        list=list.stream().peek((stu)->{
            Class aClass = classList.stream().filter((cla) -> stu.getCid() == cla.getId()).collect(Collectors.toList()).get(0);
            stu.setClazz(aClass);
        }).collect(Collectors.toList());
        return list;
    }
    @PostMapping("/add")
    public void add(@RequestBody Student stu){
        ss.save(stu);
    }

    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable("id") int id){
        ss.removeById(id);
    }
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        List<Student> list = ss.list();
        ExportParams params = new ExportParams("所有的学生数据","学生信息");
        Workbook workbook = ExcelExportUtil.exportExcel(params, Student.class, list);
        response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode("student.xls","utf-8"));
        workbook.write(response.getOutputStream());
    }
    @PostMapping("/importExcel")
    public void importExcel(MultipartFile excelFile) throws Exception {
        InputStream inputStream = excelFile.getInputStream();
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        importParams.setHeadRows(1);
        List<Student> stuList = ExcelImportUtil.importExcel(inputStream, Student.class, importParams);

        for (Student stu : stuList) {
            ss.save(stu);
        }
    }
}

